package com.itobase.statusDetect.Controller;

import com.itobase.statusDetect.Model.Camera;
import com.itobase.statusDetect.Model.Classroom;
import com.itobase.statusDetect.Repository.CameraRepository;
import com.itobase.statusDetect.Repository.ClassroomRepository;
import com.itobase.statusDetect.Service.CameraService;
import com.itobase.statusDetect.Util.Message;
import com.itobase.statusDetect.template.Constant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.InvalidParameterException;
import java.util.List;
import java.util.Map;

/**
 * @author htyu
 * @date 2019/2/24
 */

@RestController
@RequestMapping("camera")
public class CameraController {

    @Autowired
    CameraRepository cameraRepository;

    @Autowired
    CameraService cameraService;

    @Autowired
    ClassroomRepository classroomRepository;


    @RequestMapping("create")
    public Message create(@RequestBody Camera camera){
        try {
            camera.setStatus(Constant.CLOSE);
            return Message.success(cameraService.create(camera));
        }catch (InvalidParameterException e){
            return Message.error("球机名重复,请勿重复添加");
        }
    }

    @RequestMapping("list")
    public Message getList(@RequestParam(required = false) String keyword){
        return Message.success(cameraService.getList(keyword));
    }

    @DeleteMapping("delete")
    public Message deleteTime(@RequestBody Map<String, List<String>> map){
        List<Classroom> list;
        List<String> ids = map.get("ids");
        for(String id : ids){
            list = classroomRepository.findByCameraID(id);
            if(list.size()==0) {
                cameraRepository.deleteById(id);
            }else{
                return Message.error("此球机已经绑定教室，不能删除");
            }
        }
        return Message.success("删除成功");
    }

    @PostMapping("restart")
    public void restart(String id){
        //TODO 重启球机
    }

    @GetMapping("detail")
    public Message getDetail(@RequestParam String id){
        return Message.success(cameraService.detial(id));
    }

    @PutMapping("update")
    public Message updateCamera(@RequestBody Camera camera){
        try{
            return Message.success(cameraService.updateCamera(camera));
        }catch (InvalidParameterException e){
            return Message.error("教室名重复,请勿重复添加");
        }
    }
}
